package com.jaypdd.shardingjdbc.config;

import com.google.common.collect.Maps;
import io.shardingjdbc.core.api.MasterSlaveDataSourceFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;

/**
 * <p>
 *  读写分离配置类
 * </p>
 *
 * @ClassName ShardingDataSourceConfig
 * @Description TODO
 * @Author jaypdd
 * @Date 2021/1/24 16:19
 * @Version v1.0.0
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(ShardingMasterSlaveConfig.class)
@ConditionalOnProperty({
		"sharding.jdbc.data-sources.mysql_master_1.jdbc-url",
		"sharding.jdbc.master-slave-rule.master-data-source-name"
})
public class ShardingDataSourceConfig {

	@Resource
	private ShardingMasterSlaveConfig shardingMasterSlaveConfig;

	/**
	 * 配置多数据源
	 * @return  返回MasterSlave主从数据源配置
	 * @throws SQLException
	 */
	@Bean
	public DataSource masterSlaveDataSource() throws SQLException {
		// 加载所有数据源
		final Map<String, DataSource> dataSourceMap = Maps.newHashMap();
		dataSourceMap.putAll(shardingMasterSlaveConfig.getDataSources());
		final Map<String, Object> newHashMap = Maps.newHashMap();
		// 创建MasterSlave数据源
		DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap,
				shardingMasterSlaveConfig.getMasterSlaveRule(), newHashMap);
		log.info("MasterSlaveDataSource Config loading Success!");
		return dataSource;
	}
}
